package com.zxs.seckillservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxs.entity.Goods;
import com.zxs.entity.Orders;
import com.zxs.seckillservice.mapper.OrdersMapper;
import com.zxs.seckillservice.service.OrderService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单表
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrderService {

    @Resource
    private GoodsServiceImpl goodsService;


    /**
     * 下订单
     * 1、查询商品库存  看商品库存
     * 2、如果商品有库存，则向订单表插入一条数据   商品库存减一
     * 3、向订单表插入一条数据
     * @param orders
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int doOrder(Orders orders) {
        //1、查询商品表
        Goods goods = goodsService.getById(orders.getGoodsId());
        //2、判断商品库存
        if (goods.getStore() <= 0) {
            //商品库存不足
            throw new RuntimeException("商品库存不足,商品ID:" + orders.getGoodsId());
        }
        //3、商品有库存，库存减一
        UpdateWrapper<Goods> goodsUpdateWrapper = new UpdateWrapper<>();
        goodsUpdateWrapper.set("store", goods.getStore() - 1);
        goodsUpdateWrapper.eq("id", orders.getGoodsId());
        boolean update = goodsService.update(goodsUpdateWrapper);
        if (!update) {
            //更新商品表失败
            throw new RuntimeException("更新商品表失败,商品ID:" + orders.getGoodsId());
        }

        //4、插入订单表
        boolean save = this.save(orders);
        if (!save) {
            //插入订单表失败
            throw new RuntimeException("插入订单表失败,商品ID:" + orders.getGoodsId());
        }
        return 1;
    }
}
